import { getPdfFromHtml } from 'UTILS/htmlToPdf';
import { CONSENT_PUBLISH, CONSENT_PUBLISH_HTML,CONSENT_CONVERT_HTML_TO_PDF } from "_SERVICES/api";
import { getStorage } from 'UTILS/util.js'
import { timeFormatter } from 'UTILS/format.js'



export default {
  data() {
    return {
      WebSign: null,
      connState: "",
      pdfBase64: "",
      hzLoading: false,
      userInfo: {}

    }
  },
  activated() {

  },
  created() {
    let userInfo = getStorage("cst_userInfo");
    this.userInfo = JSON.parse(userInfo) || {}

  },
  beforeDestroy() {
    this.DisconnSign();
  },
  methods: {
    savePdf() {

      let errorStr = this.checkParams()
      if (errorStr) {
        this.$alert(errorStr, '必填字段提醒', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
          callback: action => {

          }
        });
        return false;
      }
      this.finishLoading = true;
      this.save(1).then((res) => {
        if (res.code && res.code == -1) {
          this.finishLoading = false;
        } else {
          let url = `http://192.168.37.6:9527/CST.html#/consentTemplate?CONSENT_ID=${this.queryInfo.CONSENT_ID}&TYPE=3&OUT_YHID=${this.userInfo.YHID}&NO_SHOW=1`
          if(process.env.VUE_APP_build_type=='production') {
            url =  `http://10.1.6.124:99/CST.html#/consentTemplate?CONSENT_ID=${this.queryInfo.CONSENT_ID}&TYPE=3&OUT_YHID=${this.userInfo.YHID}&NO_SHOW=1`
          }
          CONSENT_PUBLISH_HTML({
            TID: this.templateInfo.TID,
            SID: this.queryInfo.CONSENT_ID || '',
            htmlUrl: url
          }).then((res)=>{
            this.finishLoading = false;
            this.$message.success("执行成功，pdf已生成");
            this.queryInfo = { CONSENT_ID: res.data.SID, TYPE: 3 }
            this.$router.replace({ query: { CONSENT_ID: res.data.SID, TYPE: 3 } });
          }).catch((e)=>{
            // this.$message.error("生成pdf失败");
            this.finishLoading = false;
          })


          // getPdfFromHtml("pdfContent", (pdf_base64, pdf) => {
          //   if (pdf_base64) {
          //     CONSENT_PUBLISH({
          //       TID: this.templateInfo.TID,
          //       SID: this.queryInfo.CONSENT_ID || '',
          //       PDF_CONTENT: pdf_base64
          //     }).then((res) => {
          //       this.finishLoading = false;
          //       this.$message.success("执行成功，pdf已生成");
          //       this.queryInfo = { CONSENT_ID: res.data.SID, TYPE: 3 }
          //       this.$router.replace({ query: { CONSENT_ID: res.data.SID, TYPE: 3 } });
          //     }).catch((res) => {
          //       this.finishLoading = false;

          //     })
          //   } else {
          //     this.$message.error("生成pdf失败");
          //     this.finishLoading = false;
          //   }
          // })

        }
      })

    },
    hzSign() {
      this.hzLoading = true;
      let url = window.location.href+'&NO_SHOW=1&OUT_YHID='+this.userInfo.YHID;
      CONSENT_CONVERT_HTML_TO_PDF({
        htmlUrl:url,
        returnBase64:true
      }).then((res)=>{
        this.hzLoading = false;
        this.pdfBase64 =res.data;

        //签名的时候才去链接
        this.connectSign(val => { 
          if(val){
            this.beginSign()
          }
        });
      }).catch((e)=>{
        this.hzLoading = false;
      })

      // getPdfFromHtml("pdfContent", pdf_base64 => {
      //   this.hzLoading = false;
      //   if (pdf_base64) {
      //     this.pdfBase64 = pdf_base64.split(",")[1];
      //     console.log(this.pdfBase64)
      //     this.beginSign()
      //   } else {
      //     this.$message.error("生成pdf失败");
      //   }
      // })
    },
    //链接
    connectSign(callback) {
      let _this = this;
      this.WebSign.Init((status) => {
        if (status) {
          console.log("链接签字版成功", status)


          this.WebSign.PdfSetOperationMode(1, function(status) {
            console.log("call PdfSetOperationMode:" + (status ? "ok" : "fail"));
          });

          this.pdfConfirm();//监听事件
          this.pdfCancel();//监听事件
        } else {
          _this.$alert("连接签字版失败，请刷新页面重试", {
            confirmButtonText: "确定",
            callback: (action) => { },
          });
        }
        this.connState = status;
        callback(status);
      });
    },
    //开始签名
    beginSign(type) {
      let _this = this;
      //base64
      var dataURL = "http://192.168.37.6:9527/pdf.pdf"
      //type=1(手写签名)  type=2(指纹) type=3(签名&指纹)
      //title: 可选参数，指定签名窗口标题提示文本，例如："title":"签名标题"
      var tags = [];

      let newArray = _this.TPL_FORMAT.filter((item) => item.type == 'sign2')
      newArray.forEach((item) => {
        tags.push({
          page: Number(item.sign_page),
          x: Number(item.sign_x),
          y: Number(item.sign_y),
          type: Number(item.sign_type),
          w: 175,
          h: 75,
          title: item.label
        })
      });

      //   tags = [
      //     {
      //         "page": 2,
      //         "x": 140,
      //         "y": 970,
      //         "type": 1,
      //         "w": 175,
      //         "h": 75,
      //         "title": "患者签名"
      //     }
      
      // ]

      if (type == 0) {
        tags = null;
      }
      console.log(tags)

      // _this.WebSign.PdfBeginSignFromURL(dataURL, tags, function (status) {
      //   console.log("call PdfBeginSign:" + (status ? "ok" : "fail"));
      // });

      _this.WebSign.PdfBeginSign(_this.pdfBase64, tags, function(status) {
        console.log("call PdfBeginSign:" + (status ? "ok" : "fail"));
      });
    },
    // https://blog.csdn.net/weixin_45295262/article/details/117041018
    // 2.a4分页导出1
    set_related_time(field_name){
      this.TPL_FORMAT.forEach((item)=>{
        if(item.field_name == field_name){
          item.field_value = timeFormatter(new Date(),4);
        }
      })
    },
   
    pdfCancel(){
      this.WebSign.onPdfCancel = (e) => {
        this.DisconnSign(); //签名取消，关闭连接
      }
    },
    pdfConfirm() {
      this.WebSign.onPdfConfirm = (e) => {
        //当以预览模式(签名标记=null)打开时，事件成员readonly=true
        if (e.readonly) {
          //预览模式下用户点击了确定
          console.log("Event:onPdfConfirm, readonly=true");
        } else {
          console.log("Event:onPdfConfirm, new pdf size:" + e.pdf.length);
          console.log("签字base64", e.tags)
          let tags = e.tags;
          let index = 0;
          this.TPL_FORMAT.forEach((item) => {
            if (item.type == 'sign2') {
              if (tags[index].blend) {
                item.field_value = "data:image/png;base64," + tags[index].blend;
                if(item.field_related) {
                  this.set_related_time(item.field_related);//设置对应的签名时间
                }
              } else {
                // item.field_value = "";
              }
              index++;
            }
          });

          this.save();//主动保存一次 防止忘记保存 (如果用户同时打开多个页面，会导致数据覆盖问题,但是我们主动关闭了签字版的链接，应该避免了这个问题了)
        }
        this.DisconnSign(); //签名完成，关闭连接

      };
    },
    DisconnSign() {
      let _this = this;
      _this.WebSign.Destroy(() => {
        console.log("签字版已关闭")
        _this.connState = "";

      });
    },


    dataURLtoBlob(base64) {
      var arr = base64.split(',');
      //var mime = arr[0].match(/:(.*?);/)[1];
      // 去掉url的头，并转化为byte
      var bytes = window.atob(base64);
      // 处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length);
      // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
      var ia = new Uint8Array(ab);

      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }

      return new Blob([ab], {
        type: "pdf"
      });
    },

    fake_click(obj) {
      var ev = document.createEvent("MouseEvents");
      ev.initMouseEvent(
        "click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null
      );
      obj.dispatchEvent(ev);
    },

    download(name, data) {
      var urlObject = window.URL || window.webkitURL || window;

      var downloadData = new Blob([data]);

      var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
      save_link.href = urlObject.createObjectURL(downloadData);
      save_link.download = name;
      this.fake_click(save_link);
    }




    // BeginSign() {
    //   let _this = this;
    //   /* eslint-disable */
    //   this.WebSign = new jSign();

    //   this.ConnSign((status) => {
    //     console.log("链接手写板状态", status);
    //     if (status) {
    //       _this.WebSign.BeginSign(function (ztbz) { });
    //     }
    //   });
    // },
    // ConnSign(callback) {
    //   let _this = this;

    //   _this.WebSign.Init(function (status) {
    //     if (status) {
    //       _this.WebSign.Status(function (status, data) {
    //         _this.model = data.model;
    //         _this.sn = data.sn;
    //       });

    //       //设置事件回调
    //       _this.WebSign.onSignConfirm = function (e) {
    //         let base64 = "data:image/png;base64," + e.img;
    //         _this.base64Img = base64;
    //         _this.signDate = timeFormatter(new Date());
    //         _this.DisconnSign();

    //       };
    //       _this.connState = 1;
    //     } else {
    //       _this.connState = 0;
    //       if (_this.connState == "0") {
    //         _this.$alert("连接签字版失败，请刷新页面重试", {
    //           confirmButtonText: "确定",
    //           callback: (action) => { },
    //         });
    //       }
    //     }
    //     callback(status);
    //   });
    // },


  }
};
